package ch.headshot.photomap.client.editor.control;

import java.util.ArrayList;
import java.util.List;

import ch.headshot.photomap.client.editor.view.GpxStructure;
import ch.headshot.photomap.client.gpx.Gpx;
import ch.headshot.photomap.client.gpx.Track;
import ch.headshot.photomap.client.gpx.TrackSegment;
import ch.headshot.photomap.client.gpx.WayPoint;
import ch.headshot.photomap.client.gpx.impl.TrackSegmentImpl;

import com.google.gwt.user.client.Command;

public class ConcatCommand implements Command {

	public void execute() {
		List<Track> selectedTracks = GpxStructure.getInstance().getSelectedTracks();
		Gpx gpx = GpxStructure.getInstance().getGpx();

		if (selectedTracks.size() < 2) {
			return;
		}

		Track firstTrack = selectedTracks.get(0);
		List<List<WayPoint>> points = new ArrayList<List<WayPoint>>();
		for (Track track : selectedTracks) {
			for (TrackSegment segment : track.getSegments()) {
				List<WayPoint> p = segment.getPoints();
				if (p != null && !p.isEmpty()) {
					points.add(p);
				}
			}
			gpx.getTracks().remove(track);
		}

		List<WayPoint> first = points.remove(0);
		List<WayPoint> result = new Simplifier().concatMultiple(first, points);

		firstTrack.getSegments().clear();
		firstTrack.getSegments().add(new TrackSegmentImpl());
		TrackSegment segment = firstTrack.getSegments().get(0);
		segment.getPoints().addAll(result);

		gpx.getTracks().add(firstTrack);

		GpxStructure.getInstance().refresh();

	}
}
